//
//  HRComposeController.swift
//  weiBo
//
//  Created by helong on 16/7/18.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class HRComposeController: UIViewController {
    var fatherView: UIView?

    //  懒加载导航栏标题label
    private lazy var titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.numberOfLines = 0
        lbl.textAlignment = .Center
        //  获取用户名
        let nameStr = HRUserAccountInfos.sharedUserAccount.accountInfo!.name!
        //  换行拼接字符串
        let str = "发微博\n\(nameStr)"
        //  获取range的方法
        let range = (str as NSString).rangeOfString(nameStr)
        var attributeStr = NSMutableAttributedString(string: str)
        
        attributeStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: range)
        
        lbl.attributedText = attributeStr
        lbl.sizeToFit()
        return lbl
        
    }()
    
    //  懒加载textView
    private lazy var textView: HRTextView = {
    
        let textView = HRTextView()
        textView.delegate = self
        textView.alwaysBounceVertical = true
        //  占位符
        textView.placeholderText = "我是一个愉快的占位符~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~"
        return textView
    }()
    
    //  懒加载底部toolbar
    private lazy var toolStackView: HRStackView = {
        //  先设置为0 后来添加约束
    let stackView = HRStackView(frame: CGRectZero)
        stackView.axis = .Horizontal
        stackView.distribution = .FillEqually
        //  设置闭包
        stackView.toolButtonClickedClosure = { [weak self] (type: ButtonType) in
            
            //  判断点击的按钮是哪个按钮
            switch type {
            case .Picture:
                print("图片")
                //  打开图片选择器,选择图片
                self?.selectPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emotion:
                print("表情")
                //  把键盘切换成表情键盘
                self?.setEmotionKeyboard()

                
            case .Add:
                print("加号")
            }
            
        
        }
    return stackView
    }()
    
    //  懒加载导航栏右边按钮
    private lazy var rightButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setTitleColor(UIColor.blackColor(), forState: .Disabled)
        btn.bounds.size = CGSize(width:50,height: 30)
        btn.addTarget(self, action: "commitWeiBo", forControlEvents: .TouchUpInside)
        return btn
    }()
    
    //  懒加载选择图片的collectionview
    private lazy var galleryView: HRGalleryView = {
        let view = HRGalleryView()
        //  设置闭包
        view.addClosure = {[weak self] in
            self?.selectPicture()
        }
        return view
    }()
    
    // 懒加载自定键盘视图
    private lazy var keyboardView: HREmotionView = {
        let view = HREmotionView()
        view.height = 216
        view.width = screenWidth()
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupNavigation()
        
        // Do any additional setup after loading the view.
    }

    // MARK: - 设置UI 添加约束
    private func setupUI(){
        view.backgroundColor = UIColor(patternImage: UIImage(named: "timeline_image_placeholder")!)
        
        //  定义闭包
        keyboardView.emotionButtonClicked = {[weak self] (type: ToolBarType) in
            switch type {
            case .Default:
                print("默认")
                
            case .Emoji:
                print("emoji")
                
            case .LXH:
                print("浪小花")
                
            }
            
        }
        //  添加监听键盘的通知UIKeyboardWillChangeFrameNotification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeKeyBoard:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //  监听表情按钮发送的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showEmotion:", name: EmotionSelectedNotification, object: nil)
        
        view.addSubview(textView)
        view.addSubview(toolStackView)
        textView.addSubview(galleryView)//把图片collectionview添加到textView中
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolStackView.snp_top)
        }
        
        toolStackView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
          make.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        
        galleryView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self.textView).offset(Margin)
            make.top.equalTo(self.textView).offset(150)
            make.size.equalTo(CGSize(width: screenWidth() - Margin * 2 , height: screenWidth() - Margin * 2 ))
        }
     
    }
    
     // MARK: - 监听表情发送的事件
    @objc private func showEmotion(noti: NSNotification) {
        //  拿到传过来的按钮
        let object = noti.object as! HREmotionButton
        //  输入表情的方法,抽取到了UItextView的分类中
        textView.inputMethod(object.emotion!)
            }
    
     // MARK: - 键盘的改变事件
    @objc private func changeKeyBoard(noti: NSNotification) {
       
        //  键盘的frame变化
       let keyboardRect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).floatValue
        let keyboardY = keyboardRect.origin.y
        //  重新计算约束
        toolStackView.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(self.view).offset(keyboardY - self.view.bounds.height)
        })
        
        UIView.animateWithDuration(Double(duration)) { () -> Void in
            //  布局改变之后重新布局子控件
            self.view.layoutIfNeeded()
        }
    }
    
    
    // MARK: - 设置导航控制器
    private func setupNavigation(){
        //  设置导航栏左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismissController")
        //  设置导航栏标题
        navigationItem.titleView = titleLabel
        //  设置导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //  默认在没文字的时候是禁用状态
        navigationItem.rightBarButtonItem?.enabled = false
    }
    // MARK: - 取消按钮点击
    @objc private func dismissController(){
        //  dismiss前去掉键盘的方法
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
   
     // MARK: - 打开图片选择器,选择图片
    private func selectPicture() {
        let imagePicker = UIImagePickerController()
        //  设置代理
        imagePicker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {//如果支持相机,就从相机中拍照
            imagePicker.sourceType = .Camera
        }else {// 如果不支持相机就从相册中取
        imagePicker.sourceType = .PhotoLibrary
        }
        //  判断设备是否支持前后摄像头
       if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        }else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
             print("支持后置摄像头")
       }else {
         print("不支持摄像头")
        }
        
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    
     // MARK: - 设置表情键盘
    /**
    根据inputView是否有值判断是否设置了自定义的键盘
    */
    private func setEmotionKeyboard(){
        //  点击键盘上的按钮获取第一响应者
        textView.becomeFirstResponder()
        if textView.inputView == nil {//如果没有设置表情键盘
            
            textView.inputView = keyboardView
            toolStackView.setEmotionButtonImage(false)
            
        }else {//如果设置了表情键盘
            
            toolStackView.setEmotionButtonImage(true)
            //  设置成系统键盘
            textView.inputView = nil
        }
        
        self.textView.reloadInputViews()
    }
    
     // MARK: - 发送微博
   @objc private func commitWeiBo() {
    //  作为拼接的字符串

    let inputString = textView.stringFromAttributedString()

    print(inputString)


    //  如果没有选图片,就发送文字
    if galleryView.galleryArray.count == 0 {
        commitTextContent(inputString)
    }else {
        commitImageContent(inputString)
    }
    }
    
     // MARK: - 发送没有配图的微博
    private func commitTextContent(inputString: String) {
        SVProgressHUD.showWithStatus("正在发送...")
        HRNetworkingTool.sharedSessionManager.commitWeiBo(inputString) { (response, error) -> Void in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                print(error)
                return
            }else {
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
                //  发送成功之后回到主页
                let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.6  * Double(NSEC_PER_SEC)))
                dispatch_after(delay, dispatch_get_main_queue(), { () -> Void in
                    self.dismissController()
                    self.fatherView?.removeFromSuperview()
 
                })
  
            }
        }
    }
    
     // MARK: - 发送带有配图的微博
    private func commitImageContent(inputString: String) {
        //   如果选了图片就发送图片和文字
        print(galleryView.galleryArray.count)
        SVProgressHUD.showWithStatus("正在发送...")
        let formData = UIImageJPEGRepresentation(galleryView.galleryArray.first!, 0.1)
        HRNetworkingTool.sharedSessionManager.commitWeiboWithPicture(inputString, formData: formData!, callBack: { (response, error) -> Void in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }else {
                SVProgressHUD.showSuccessWithStatus("发送成功")
                //  发送成功之后回到主页
                SVProgressHUD.showSuccessWithStatus("发送成功")
                //  发送成功之后回到主页
                let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.6  * Double(NSEC_PER_SEC)))
                dispatch_after(delay, dispatch_get_main_queue(), { () -> Void in
                    
                    self.dismissController()
                    self.fatherView?.removeFromSuperview()
                    
                })
            }
        })
    }
    
    //  释放控制器
    deinit{
        //  移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}

 // MARK: - 实现UIImagePickerControllerDelegate代理方法
extension HRComposeController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 保存选中的图片,此处图片会很大,需要压缩
      let newImage = image.produceImageWithScale(200)
        galleryView.addImage(newImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        //  选中图片之后显示collectionview
        
    }
     // MARK: - 压缩图片的方法(移动到了UIImage的分类中)
//    /**
//    根据指定的宽度缩放图片
//    
//    - parameter image:       要缩放的图片
//    - parameter scaledWidth: 缩放的宽度
//    
//    - returns: 缩放好的图片
//    */
//    private func produceImageWithScale(image: UIImage, scaledWidth: CGFloat) -> UIImage {
//        
//        let scaledHeight = image.size.height / image.size.width  * scaledWidth
//        let size = CGSize(width: scaledWidth, height: scaledHeight)
//        //  开启
//         UIGraphicsBeginImageContext(size)
//        
//        image.drawInRect(CGRect(origin: CGPointZero, size: size))
//        let targetImage = UIGraphicsGetImageFromCurrentImageContext()
//        //  关闭
//        UIGraphicsEndImageContext()
//        
//        return targetImage
//        
//    }
//    
}


 // MARK: - textView的代理方法
extension HRComposeController: UITextViewDelegate {
     // MARK: - textView文字变化
    func textViewDidChange(textView: UITextView) {
        if textView.hasText() {
            navigationItem.rightBarButtonItem?.enabled = true
        } else {
            navigationItem.rightBarButtonItem?.enabled = false
        }
    }
    
     // MARK: - textview拖动
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //  如果向下滑动隐藏键盘,如果向上滑动弹出键盘
        if scrollView.contentOffset.y > 0 {
            textView.becomeFirstResponder()
        } else {
            textView.resignFirstResponder()
        }
    }
}
